package org.systemsbiology.addama.sequencing.controllers;

import org.apache.commons.httpclient.DefaultHttpMethodRetryHandler;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.springframework.mail.MailSender;
import org.springframework.mail.SimpleMailMessage;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.protocol.Protocol;
import org.json.JSONObject;
import org.systemsbiology.addama.commons.httpclient.support.ResponseCallback;
import org.systemsbiology.addama.commons.httpclient.support.HttpClientResponseException;
import org.systemsbiology.addama.commons.httpclient.support.HttpClientTemplate;
import org.systemsbiology.addama.commons.httpclient.support.IsExpectedStatusCodeResponseCallback;
import org.systemsbiology.addama.commons.httpclient.support.ssl.EasySSLProtocolSocketFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: jlin
 * Date: Aug 31, 2010
 * Time: 2:22:38 PM
 * To change this template use File | Settings | File Templates.
 */
public class LIMSAbstractController {

    protected MailSender mailSender;
    protected SimpleMailMessage templateMessage;
    protected String addamaDudleyUser;
    protected String addamaDudleyPassword;
    protected String solrHost;
    private static final Logger log = LoggerFactory.getLogger(LIMSAbstractController.class);   

    public void setMailSender(MailSender mailSender) {
        this.mailSender = mailSender;
    }

    public void setTemplateMessage(SimpleMailMessage templateMessage) {
        this.templateMessage = templateMessage;
    }

    public String getAddamaDudleyUser() {
        return addamaDudleyUser;
    }

    public String getAddamaDudleyPassword() {
        return addamaDudleyPassword;
    }

    public void setAddamaDudleyUser(String addamaDudleyUser) {
        this.addamaDudleyUser = addamaDudleyUser;
    }

    public void setAddamaDudleyPassword(String addamaDudleyPassword) {
        this.addamaDudleyPassword = addamaDudleyPassword;
    }

    public String getSolrHost() {
        return solrHost;
    }

    public void setSolrHost(String solrHost) {
        this.solrHost = solrHost;
    }


    protected String getBaseUrl(HttpServletRequest request) {
        StringBuilder builder = new StringBuilder();
        builder.append("http://");
        builder.append(request.getServerName());
        int port = request.getServerPort();
        if (port != 80) {
            builder.append(":").append(port);
        }
        return builder.toString();
    }

    protected String getHttpsUrl(HttpServletRequest request) {
        StringBuilder builder = new StringBuilder();
        builder.append("https://");
        builder.append(request.getServerName());
        builder.append(":").append("8443");
        return builder.toString();
    }   

    public void postSolrUpdate(String url, JSONObject jsonObject) {
           try {
               log.info("Begin postSolrUpdate" + new Date());
               HttpClient client = new HttpClient();
               PostMethod post = new PostMethod(url);
               post.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                       new DefaultHttpMethodRetryHandler(3, false));
               JSONObject postObject = new JSONObject();
               postObject.put("doc", jsonObject);
               JSONObject addObject = new JSONObject();
               addObject.put("add", postObject);
               post.setParameter("jsonData", "application/json");
               post.setRequestEntity(new StringRequestEntity(addObject.toString(), "application/json", null));
               post.setRequestHeader("Content-Type", "application/json");
               int statusCode = client.executeMethod(post);
               System.out.println("Post " + url + "\nStatus code:" + statusCode);
               System.out.println(IOUtils.toString(post.getResponseBodyAsStream(), "UTF-8"));
               post.releaseConnection();
               log.info("Done postSolrUpdate" + new Date());
           } catch (IOException e) {
               e.printStackTrace();
           } catch (JSONException ej) {
               ej.printStackTrace();
           }
       }

     public JSONObject getSolr(String url) {
        try {
            HttpClient client = new HttpClient();
            GetMethod get = new GetMethod(url);
            get.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                    new DefaultHttpMethodRetryHandler(3, false));
            int statusCode = client.executeMethod(get);
            log.info("Get SOLR" + url + "\nStatus code:" + statusCode);
           // System.out.println(IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8"));
            JSONObject resp = new JSONObject(IOUtils.toString(get.getResponseBodyAsStream(), "UTF-8"));
            //{"response":{"start":0,"docs":[{"limsadminYoMaxNum":512,"limsKey":"dudley_limsadminkey","limsadminYadBoxNum":6,"limsadminLOligoCount":240,"limsadminYpgPosition":"A1","limsadminYoBoxNum":7,"limsadminYseqCount":73,"limsadminYseqRADCount":52,"limsadminYadMaxNum":424,"limsadminYseqOligoCount":13,"limsadminKey":"dudley_limsadminkey","limsadminYpgMaxNum":1768,"limsadminChemCount":367,"limsadminYcgsCount":6,"limsadminDOligoMaxNum":532,"limsadminPlasmidBoxNum":4,"limsadminYoPosition":"G3","limsadminChemMaxNum":367,"limsadminDOligoCount":532,"limsadminYadCount":424,"limsadminYadPosition":"B9","limsadminCrossingCount":12,"limsadminLOligoMaxNum":240,"limsadminYpgCount":1768,"limsadminYoCount":791,"limsadminPlasmidMaxNum":323,"limsadminPlasmidCount":323,"allFields":["dudley_limsadminkey","791","512","7","G3","424","424","6","B9","1768","1768","20","A1","367","367","532","532","240","240","323","323","4","12","73","13","52","6"],"limsadminYpgBoxNum":20}],"numFound":1},"responseHeader":{"status":0,"QTime":2,"params":{"q":"limsadminKey:dudley_limsadminkey","wt":"json"}}}
            //JSONObject respObject = resp.getJSONObject("response");
            //JSONArray jsonArray = respObject.getJSONArray("docs");
            //JSONObject adminObj = (JSONObject)jsonArray.get(0);
            //System.out.println("AdminObj:" + adminObj);
            get.releaseConnection();
            return resp.getJSONObject("response");
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        } catch (JSONException ej) {
            ej.printStackTrace();
            return null;
        }
    }

}
